{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 字符串压缩\n",
    "\n",
    "[![Author](https://img.shields.io/badge/Author-%40mjd507-important?style=social&logo=GitHub)](https://github.com/mjd507)\n",
    "[![WeChat Channel](https://img.shields.io/badge/Wechat-Daily%20Problem-important?style=social&logo=WeChat)](https://mp.weixin.qq.com/s/agZdhuoWWic3RDpxhspdeg)\n",
    "\n",
    "![Logo](img/Day80-1.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "　　给定一串带有重复的字符串，执行原地压缩。压缩后的字符串长度应当小于或等于原始字符串。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 用例说明\n",
    "\n",
    "```python\n",
    "In[1]: ['a', 'a', 'b', 'c', 'c', 'c']\n",
    "Out[1]: ['a', '2', 'b', 'c', '3']\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Solution(object):\n",
    "    def compress(self, chars: list) -> list:\n",
    "        # Index pointers\n",
    "        left = i = 0\n",
    "        while i < len(chars):\n",
    "            # Current character\n",
    "            char = chars[i]\n",
    "            length = 1\n",
    "            # Check the next character\n",
    "            while i + 1 < len(chars) and char == chars[i + 1]:\n",
    "                length += 1\n",
    "                i += 1\n",
    "            chars[left] = char\n",
    "            if length > 1:\n",
    "                chars = chars[:left + 1] + [str(length)] + chars[left + length:]\n",
    "                left += 1\n",
    "            left += 1\n",
    "            i += 1\n",
    "        return chars"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['a', '2', 'b', 'c', '3']\n"
     ]
    }
   ],
   "source": [
    "print(Solution().compress(['a', 'a', 'b', 'c', 'c', 'c']))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
